package com.itheima.service;


        import com.alibaba.dubbo.config.annotation.Service;
        import com.github.pagehelper.Page;
        import com.github.pagehelper.PageHelper;
        import com.itheima.dao.PermissionDao;
        import com.itheima.dao.RoleDao;
        import com.itheima.dao.UserDao;
        import com.itheima.entity.PageResult;
        import com.itheima.entity.QueryPageBean;
        import com.itheima.pojo.Permission;
        import com.itheima.pojo.Role;
        import com.itheima.pojo.User;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
        import org.springframework.transaction.annotation.Transactional;

        import java.util.HashMap;
        import java.util.List;
        import java.util.Map;
        import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    public User findByUsername(String username) {

        //根据username查询到user
        User user = userDao.findByUsername(username);
        if (user != null) {
            //根据userId查询到角色集合
            Set<Role> roleSet = roleDao.findByUserId(user.getId());
            System.out.println("roleSet = ====================================" + roleSet);
            if (roleSet != null && roleSet.size() > 0) {
                //遍历集合 查询到每一个角色对应的权限
                for (Role role : roleSet) {
                    System.out.println(role.getId() + "=======================================================");
                    Set<Permission> permissionSet = permissionDao.findByRoleId(role.getId());
                    if (permissionSet != null && permissionSet.size() > 0) {

                        //添加权限到role中
                        role.setPermissions(permissionSet);
                    }
                }
                //添加角色到user中
                user.setRoles(roleSet);
            }
        }
        return user;
    }

    //添加用户
    @Override
    public Integer add(User user, Integer[] roleIds) {

//        首先查询是否存在重复用户名
        Integer count = userDao.findCountByUsername(user.getUsername());
        if (count > 0) {
            throw new RuntimeException("用户名已存在");
        }
        //插入user 获取userId
        String password = user.getPassword();
        user.setPassword(passwordEncoder.encode(password));
        Integer insertCount = userDao.add(user);
        Integer userId = user.getId();
        //根据userid 插入关联的role
        if (roleIds != null && roleIds.length > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", userId);
            for (Integer roleId : roleIds) {
                map.put("role_id", roleId);
                userDao.addUserAndRole(map);
            }
        }
        return insertCount;
    }
    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();

        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        if (queryString == null || queryString.trim().equals("")) {
            queryString = "";
        }

        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findByCondition("%" + queryString.trim() + "%");
        return new PageResult(page.getTotal(), page.getResult());

    }

    //根据id 查询用户
    @Override
    public User findById(Integer id) {
        //先查询出user
        User user = null;
        if (id != null) {
            user = userDao.findById(id);
        }
        List<Integer> roleIds = null;
        if (user != null) {
            roleIds = userDao.findRoleIds(user.getId());
        }

        if (roleIds != null && roleIds.size() > 0) {
            user.setRoleIds(roleIds);
        }

        //根据userid 查询出role
        return user;
    }

    //删除用户
    @Override
    public Integer deleteById(Integer id) {
        int count = 0;
        if (id != null) {
            userDao.deleteRoleAndUserById(id);
            count = userDao.deleteById(id);
        }
        return count;
    }

    //编辑用户
    @Override
    public Integer edit(User user, Integer[] roleIds) {
        Integer userId = user.getId();
        //根据userid 删除关联的role
        userDao.deleteRoleAndUserById(userId);

        //插入user 获取userId 加密
        String password = user.getPassword();
        user.setPassword(passwordEncoder.encode(password));
        //编辑user
        Integer editCount = userDao.edit(user);
        //根据userid 插入关联的role
        if (roleIds != null && roleIds.length > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("user_id", userId);
            for (Integer roleId : roleIds) {
                map.put("role_id", roleId);
                userDao.addUserAndRole(map);
            }
        }
        return editCount;

    }


}
